package com.johnzer.frame.mvp;

import com.johnzer.frame.utils.rxjava.BaseSubscriber;

import java.util.LinkedList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Author   : johnzer
 * Data     : 2016-09-05  10:56
 * Describe :
 */

public abstract class BasePresenter<V extends IView, M extends IModel> implements IPresenter {

    protected V iView;

    protected M model;

    private List<Disposable> disposables = new LinkedList<>();

    public BasePresenter(V view) {
        this.iView = view;
        model = createModel();
    }

    /**
     *  使用這個方法需要注意 使用實現subscriber接口在裡面去將 Disposable dispose()
     * @param observable
     * @param subscriber
     * @param <T>
     */
    @Deprecated
    public <T> void $subScriber(Observable<T> observable, Observer<T> subscriber) {
        observable.subscribe(subscriber);
//        disposables.add(observable.subscribe(subscriber));
    }
    @Deprecated
    public <T> void $subScriber(Observable<T> o, Consumer<T> action1) {
        disposables.add(o.subscribe(action1));
    }
    public <T> void $subScriber(Flowable<T> flowable, Consumer<T> action1) {
        disposables.add(flowable.subscribe(action1));
    }

    /**
     * @param flowable
     * @param subscriber
     * @param <T>
     */
    public <T> void $subScriber(Flowable<T> flowable, BaseSubscriber<T> subscriber) {
        disposables.add(flowable.subscribe(subscriber.getNext(),subscriber.getError(),subscriber.getOnComplete(),subscriber.getOnSubscribe()));
    }

    public void addDisposable(Disposable disposable){
        disposables.add(disposable);
    }

    protected abstract M createModel();

    @Override
    public void detachView() {
        for (Disposable s : disposables) {
            if (s != null && !s.isDisposed()) {
                s.dispose();
            }
        }
        this.iView = null;
    }

}
